import { reactive, ref, watch } from "vue";
import { deleteCompeteAPI, getCompeteAPI } from "@/api/resource.ts";
import { ElMessage } from "element-plus";

export default function useCompete() {

  const competeList = ref([])
  const listDialog = ref()
  const uploadDialog = ref()
  const selectValue = ref('2')
  const dialog = ref()
  const query = reactive({
    page: 1,
    limit: 10,
    type: 2
  })

  // 获取竞赛列表
  const getCompete = async () => {
    const res = await getCompeteAPI(query)
    competeList.value = res.data.list
  }

  // 添加竞赛
  const addCompete = () => {
    dialog.value.init({}, 0)
  }

  // 编辑竞赛
  const editCompete = (row: any) => {
    dialog.value.init(row, 1)
  }

  // 查看报名
  const handleLook = (row: any) => {
    listDialog.value.init(row)
  }

  // 删除竞赛
  const deleteCompete = async (id: string) => {
    const res: any = await deleteCompeteAPI(id)
    ElMessage({
      type: res.code === 0 ? 'success' : 'error',
      message: res.message
    })
  }

  watch(selectValue, async (newValue) => {
    query.type = parseInt(newValue)
    await getCompete()
  })

  // 是否在当前时间之前
  const isBeforeNow = (time: string) => {
    const givenDate = new Date(time);
    const currentDate = new Date();
    return givenDate < currentDate;
  }

  // 上传成绩
  const uploadScore = (id: string) => {
    uploadDialog.value.init(id)
  }

  return {
    dialog,
    listDialog,
    uploadDialog,
    selectValue,
    competeList,
    isBeforeNow,
    uploadScore,
    getCompete,
    addCompete,
    editCompete,
    handleLook,
    deleteCompete
  }
}
